import * as step from '@flow-step/step-toolkit'
import * as OSS from './oss-upload'
import * as fs from 'fs'
import * as inputCheck from './input-check'
import * as upload from './package-upload'
import path from 'path'
import mdFile from 'md5-file'
import {UploadInputs} from './upload-inputs'

export async function execute(): Promise<void> {
    let uploadInputs = await getUploadInputs()
    //上传
    if (uploadInputs.uploadType === 'PACKAGES' || uploadInputs.uploadType === 'packages') {
        //上传packages
        await upload.artifactUpload(uploadInputs)
        await upload.uploadMetaData(uploadInputs)
    } else {
        //上传OSS
        await OSS.put(uploadInputs)
    }
}

export async function getUploadInputs(): Promise<UploadInputs> {
    const input = await inputCheck.getInputs()
    let artifactFullName = path.join(input.artifactPath, input.artifactName)

    let stat
    try{
        stat = fs.statSync(artifactFullName)
    }catch (e){
        step.error(`failed to resolve ${artifactFullName}`)
        throw e
    }
    if (stat.isDirectory()){
        throw new Error(`${artifactFullName} should refer to a file, not directory`)
    }

    input.fileMD5 = mdFile.sync(`${artifactFullName}`)
    input.artifactFullName = artifactFullName
    return input
}
